﻿namespace Sitecore.ChangesTracker.Commands
{
  using System;
  using System.Collections.Specialized;
  using System.Linq;
  using Sitecore;
  using Data.Archiving;
  using Diagnostics;
  using Globalization;
  using Text;
  using Web.UI.Sheer;
  using Web.UI.WebControls;
  using Web.UI.XamlSharp.Continuations;
  using Sitecore.Web;
  using Sitecore.ChangesTracker.Exceptions;

  public class Restore : Shell.Framework.Commands.Command, ISupportsContinuation
  {
    public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
    {
      Assert.ArgumentNotNull(context, "context");
      string str = context.Parameters["item"];
      
      if (string.IsNullOrEmpty(str))
      {
        SheerResponse.Alert("Select an item first.", new string[0]);
      }
      else
      {
        NameValueCollection parameters = new NameValueCollection();
        parameters["item"] = str;
        parameters["archivename"] = context.Parameters["archivename"];
        parameters["close"] = context.Parameters["close"];
        ClientPipelineArgs args = new ClientPipelineArgs(parameters);
        if (ContinuationManager.Current != null)
        {
          ContinuationManager.Current.Start(this, "Run", args);
        }
        else
        {
          Context.ClientPage.Start(this, "Run", args);
        }
      }
    }
    public override string GetClick(Shell.Framework.Commands.CommandContext context, string click)
    {
      
      string clc = base.GetClick(context, click);
      if (click.Contains("app=compare"))
      {
        int ind = clc.IndexOf(')');
        string param = "item=" + context.Parameters["arc_id"] + ",archivename=" + context.Parameters["archivename"];
        if (ind > 0)
        {
          clc = clc.Insert(ind, "," + param);
        }
        else
        {
          clc = "(" + param + ")";
        }
      }
      return clc;
    }

    public void Run(ClientPipelineArgs args)
    {
      Assert.ArgumentNotNull(args, "args");
      if (args.IsPostBack)
      {
        if (args.Result == "yes")
        {
          Archive archive = ArchiveManager.Providers["changetracker"].GetArchive(args.Parameters["archivename"], Context.ContentDatabase);
          Assert.IsNotNull(archive, typeof(Archive));
          int num = 0;
          ListString str = new ListString(args.Parameters["item"]);
          foreach (string str2 in str)
          {
            Guid archivalId = new Guid(str2);
            try
            {
              archive.RestoreItem(archivalId);
              Log.Audit(this, "Restore: archive: {0}, id: {1}", new string[] { archive.Name, archivalId.ToString() });
              continue;
            }
            catch (TemplateChangedException e)
            {
              Log.Error(string.Format("Restore: failed to restore: {0}, error: {1}", str2, e.Message), this);
              SheerResponse.Alert(Translate.Text("{0} item could not be restored because its template has been changed.", new object[] { e.ItemPath }), new string[0]);
              continue;
            }
            catch (Exception exception)
            {
              num++;
              Log.Error(string.Format("Restore: failed to restore: {0}, error: {1}", str2, exception.Message), this);
              continue;
            }
            
          }

          if (num > 0)
          {
            SheerResponse.Alert(Translate.Text("{0} items could not be restored because of either security permissions or errors.", new object[] { num }), new string[0]);
          }

          if (args.Parameters["close"] == "1")
          {
            SheerResponse.Eval("if(window.parent!=null&&window.parent.parent!=null&&window.parent.parent.scManager!= null){window.parent.parent.scManager.closeWindow(window.parent);}else{window.close()}");
          }
          else
          {
            SheerResponse.SetLocation(string.Empty);
          }
        }
      }
      else
      {
        ListString str3 = new ListString(args.Parameters["item"]);
        if (str3.Count == 1)
        {
          Archive archive2 = ArchiveManager.Providers["changetracker"].GetArchive(args.Parameters["archivename"], Context.ContentDatabase);
          Assert.IsNotNull(archive2, typeof(Archive));
          ArchiveQuery query = new ArchiveQuery();
          query.ArchivalId = new Guid(str3[0]);

          ArchiveEntry entry = archive2.GetEntries(query, 0, 1).FirstOrDefault<ArchiveEntry>();
          if (entry == null)
          {
              SheerResponse.Alert("Item not found.", new string[0]);
              return;
          }

          string name = entry.Name;
          SheerResponse.Confirm(Translate.Text("Do you want to restore \"{0}\"?", new object[] { name }));
        }
        else
        {
          SheerResponse.Confirm(Translate.Text("Do you want to restore these {0} items?", new object[] { str3.Count }));
        }

        args.WaitForPostBack();
      }
    }
  }
}

